package com.cskaoyan._03jdbc.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author Macro_Ray
 * @since 2024/4/17 下午4:30
 */
public class JdbcUtils {
    private static String url;
    private static String username;
    private static final String password;

    // 读取配置文件
    static{
        // 因为properties配置文件不需要频繁改动，所以直接读取一次
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("02-JavaEE/jdbc.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }
    // 工具类中的异常可以直接抛出，因为调用者需要处理异常
    public static Connection getConnection() throws SQLException {
        // 1.注册驱动
//        DriverManager.registerDriver(new Driver());
        try {
            Class.forName("com.mysql.cj.jdbc,Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 2.获取连接
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }

    // 释放资源，关闭连接
    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if (connection != null) {
            connection.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (resultSet != null) {
            resultSet.close();
        }
    }
}
